<?php
namespace app\tour\controller;

use app\admin\model\Appraise as App;
use app\common\model\LogOrderModel as lo;
use app\common\model\OrderCancelModel as ocm;
use app\tour\model\Order as orderModel;
use think\Db;
use think\Request;
use think\Session;

class Order extends Common
{
    public function order()
    {

        if (Request::instance()->isAjax()) {

            $get = Request::instance()->get();

            $where = [];

            if (isset($get['order_sn']) && $get['order_sn'] != '') {
                $where['t1.order_sn'] = $get['order_sn'];
            }

            if (isset($get['order_status']) && $get['order_status'] != '') {

                $where['order_status'] = $get['order_status'];
            } else {
                $where['order_status'] = ['in', [3, 4]];
            }

            if (isset($get['selectdate']) && $get['selectdate'] != '') {
                $datestart            = strtotime(substr($get['selectdate'], 0, 10));
                $dateend              = strtotime(substr($get['selectdate'], 13, 10) . '+1day');
                $where['t1.create_time'] = array('between', array($datestart, $dateend));
            }

            $count = orderModel::orderList(array(), $where, 0, 0, true);

            $pagesize = $get['limit'];
            $page     = (int) $get['page'];
            $startrow = ($page - 1) * $pagesize;
           
            $field = [];
            $data  = orderModel::orderList($field, $where, $startrow, $pagesize, false);


//            foreach ($data as $k => $v) {
//
//                $data[$k]['ticket_date'] = date('Y-m-d H:i:s', $v['ticket_date']);
//                $data[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
//
//            }

            foreach ($data as $k => $v) {

             //   $data[$k]['ticket_date'] = date('Y-m-d H:i:s', $v['ticket_date']);
               // $data[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);

            }


            return ['code' => 0, 'msg' => '', 'count' => $count, 'data' => $data];

        } else {
            $where['t1.order_status'] = ['in', [3, 4]];
            $res = Db::name('tour_order')->alias('t1')
                ->field('t1.order_sn')
                ->join('order_cancel t2', 't1.order_id=t2.order_id', 'left')
                ->join('tour_admin t3', 't2.cancel_id = t3.t_admin_id', 'left')->where('t1.tour_id', Session::get('tour_id'))
                ->where('t1.is_del', 0)
                ->where($where)
                ->select();
            $this->assign('res',$res);
            return view();

        }

    }

    /*
     * 核销页面
     */
    public function cancel()
    {
        if (Request::instance()->isAjax()) {
            $pagedata = Request::instance()->get();
            $pagesize = $pagedata['limit'];
            $page     = (int) $pagedata['page'];
            if ($page == 1) {
                $startrow = 0;
            } else {
                $startrow = ($page - 1) * $pagesize;
            }
            $where['order_status'] = array('eq', 1);
            if (isset($pagedata['cancel_code']) && $pagedata['cancel_code'] != '') {
                $where['cancel_code'] = ['eq', "tour_cancle_code_" . $pagedata['cancel_code']];

            }
            $field = [];
            $data  = orderModel::orderList($field, $where, $startrow, $pagesize, false);
            foreach ($data as $k => $v) {
                $data[$k]['cancel_code'] = substr($v['cancel_code'], -8);
            }
            $count = orderModel::orderList(array(), $where, 0, 0, true);
            return json(array('code' => 0, 'msg' => '请求成功', 'count' => $count, 'data' => $data));
        } else {
            return view();
        }
    }

    /*
     * 确认核销
     */
    public function cancelPass()
    {
        if (Request::instance()->isAjax()) {
            $postData = input('param.');
            //先查询一下订单是否已经被核销了
            $order = Db::name('tour_order')->alias('a')
            ->field('a.order_id,a.order_sn,a.order_status,t.no_settled_order_fee,a.ticket_price,a.ticket_count,a.commission_rate,t.no_settled_order_num,a.order_price,a.ticket_date')
            ->join('tours t','a.tour_id=t.tour_id','left')->where('order_id', $postData['id'])->find();
            if ($order) {
                Db::startTrans();
                try {
                    if($order['order_status']==7){
                        return 7;
                    }
                    if ($order['order_status'] != 1) {
                        return 2;
                    }
                    //处理今天的时间戳
                    $beginToday=mktime(0,0,0,date('m'),date('d'),date('Y'));
                    $endToday=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
                   
                   
                    //判断是否是今天的
                    if($order['ticket_date']<$beginToday || $order['ticket_date']>$endToday){
                        return 4;
                    }
                    //计算订单佣金
                    $commissionFee = 0;
                    if ($order['commission_rate'] > 0) {
                        $commissionFee = $order['ticket_price'] * $order['ticket_count'] * $order['commission_rate'] / 1000;

                    }
                  
                    // 核销该订单信息
                    $OrderCancel = new ocm();
                    $OrderCancel->orderCancel(Session::get('t_admin_id'), 1, $order['order_id'], $order['order_sn'],$order['order_price']);
                    //创建订单日志
                    $logOrder = new lo();
                    $logOrder->addLogOrder($order['order_id'], 2, Session::get('t_admin_id'), 3, '核销成功');
                    //修改商家未计算订单数和未结算的订单佣金
                    Db::name("tours")
                        ->where("tour_id", Session::get('tour_id'))
                        ->setInc("no_settled_order_num", 1);


                    Db::name("tours")
                        ->where("tour_id", Session::get('tour_id'))
                        ->setDec('no_settled_order_fee',$commissionFee);

                    $data = [
                        'order_status'   => 3,
                        'commission_fee' => $commissionFee,
                    ];
                    //修改订单状态
                    $res = Db::name('tour_order')->where('order_id', $postData['id'])->update($data);
                    if ($res) {

                        Db::commit();
                        return 0;
                    } else {
                        Db::rollback();
                        return 1;
                    }

                } catch (\Exection $e) {
                    Db::rollback();

                    return 1;
                }
            } else {
                return 1;
            }

            // if($res){
            //     //插入到核销表
            //     $data = [
            //         'cancel_id'=>Session::get('t_admin_id'),
            //         'order_sn'=>$postData['sn'],
            //         'order_id'=>$postData['id'],
            //         'create_time'=>date('Y-m-d H:i:s'),
            //         'type'=>1,
            //         'money'=>$postData['money']

            //     ];
            //     $res = Db::name('order_cancel')->insertGetId($data);
            //     if($res){
            //         return 0;
            //     }else{
            //         return 1;
            //     }
            // }else{
            //     return 1;
            // }
        }
    }

    public function cancel_order()
    {
        if (Request::instance()->isAjax()) {
            $pagedata = Request::instance()->get();
            $pagesize = $pagedata['limit'];
            $page     = (int) $pagedata['page'];
            if ($page == 1) {
                $startrow = 0;
            } else {
                $startrow = ($page - 1) * $pagesize;
            }
            $where['type'] = array('eq', 1);
            if (isset($pagedata['order_sn']) && $pagedata['order_sn'] != '') {
                $where['order_sn'] = array('like', '%' . $pagedata['order_sn'] . '%');

            }
            if (isset($pagedata['admin_rename']) && $pagedata['admin_rename'] != '') {

                $where['admin_rename'] = array('like', '%' . $pagedata['admin_rename'] . '%');

            }
            if (isset($pagedata['search_start_time']) && $pagedata['search_start_time'] != '') {
                $datestart            = strtotime(substr($pagedata['search_start_time'], 0, 10));
                $dateend              = strtotime(substr($pagedata['search_start_time'], 13, 10));
                $where['a.create_time'] = array('between time', array($datestart, $dateend));
            }
            $id   = Session::get('tour_id');
            $data = Db::name('order_cancel')->alias('a')
                ->field('a.*,t.admin_rename')
                ->join('tour_admin t', 'a.cancel_id = t.t_admin_id', 'LEFT')
                ->where('t.tour_id', $id)
                ->where($where)
                ->order('a.id','desc')
                ->limit($startrow, $pagesize)
                ->select();
            // $data = OrderModel::getOrderList($id,$where,$startrow,$pagesize);
            Session::set('data', $data);
            $count = Db::name('order_cancel')->alias('a')
                ->field('a.*,t.admin_rename')
                ->join('tour_admin t', 'a.cancel_id = t.t_admin_id', 'LEFT')
                ->where('t.tour_id', $id)
                ->where($where)
                ->count();
            return json(array('code' => 0, 'msg' => '请求成功', 'count' => $count, 'data' => $data));
        } else {
            //查询是这个商户下的所有姓名
            $res = Db::name('tour_admin')
                ->field('admin_rename')
                ->where('tour_id', Session::get('tour_id'))
                ->where('is_use', 1)
                ->where('is_del', 0)
                ->select();
            $where['type'] = array('eq', 1);
            $order = Db::name('order_cancel')->alias('a')
                ->field('a.order_sn')
                ->join('tour_admin t', 'a.cancel_id = t.t_admin_id', 'LEFT')
                ->where('t.tour_id', Session::get('tour_id'))
                ->where($where)
                ->order('id','desc')
                ->select();
            $this->assign('order',$order);
            $this->assign('res', $res);
            return view();
        }
    }

    /**
    查看评价
     */
    public function getAppInfo()
    {
        if (Request::instance()->isAjax()) {
            $post              = Request::instance()->post();
            $where['order_id'] = ['eq', $post['order_id']];
            $where['type']     = ['eq', $post['type']];
            $app               = new App();
            $res               = $app->getAppInfo($where);
            if (!empty($res)) {
                $res['create_time'] = date('Y-m-d H:i:s', $res['create_time']);
                if ($res['eval_status'] == 1) {
                    $res['eval_status'] = "好评";
                } else {
                    $res['eval_status'] = "差评";
                }

                $res['images'] = explode(',', $res['images']);
            }

            if ($res) {
                return json(array('code' => 1, 'msg' => '返回成功', 'data' => $res));
                // ajax_return(1,'返回成功',$res);
            } else {
                return json(array('code' => 0, 'msg' => '暂无评价', 'data' => $res));
            }
        }
    }

    public function refundorder(){


        if (Request::instance()->isAjax()) {

            $get = Request::instance()->get();

            $where = [];

            if (isset($get['order_sn']) && $get['order_sn'] != '') {
                $where['order_sn'] = $get['order_sn'];
            }

            if (isset($get['order_status']) && $get['order_status'] != '') {

                $where['order_status'] = $get['order_status'];
            } else {
                $where['order_status'] = ['in', [3, 4]];
            }

            if (isset($get['selectdate']) && $get['selectdate'] != '') {
                $datestart            = strtotime(substr($get['selectdate'], 0, 10));
                $dateend              = strtotime(substr($get['selectdate'], 13, 10) . '+1day');
                $where['create_time'] = array('between', array($datestart, $dateend));
            }

            $count = orderModel::orderList(array(), $where, 0, 0, true);

            $pagesize = $get['limit'];
            $page     = (int) $get['page'];
            $startrow = ($page - 1) * $pagesize;

            $field = [];
            $data  = orderModel::orderList($field, $where, $startrow, $pagesize, false);

            foreach ($data as $k => $v) {

                $data[$k]['ticket_date'] = date('Y-m-d H:i:s', $v['ticket_date']);
                $data[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);

            }

            return ['code' => 0, 'msg' => '', 'count' => $count, 'data' => $data];

        } else {

            return view();

        }
    }

}
